const { registerPlugin } = wp.plugins;
const { PluginSidebar, PluginSidebarMoreMenuItem } = wp.editPost;
const { PanelBody, TextareaControl, Button, ButtonGroup, Notice } = wp.components;
const { useState } = wp.element;
const { dispatch, select } = wp.data;

const AIWriterPlugin = () => {
    const [prompt, setPrompt] = useState('');
    const [mode, setMode] = useState('instruction');
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState('');

    const generateContent = async () => {
        if (!prompt.trim() && mode === 'instruction') {
            setError('请输入提示词');
            return;
        }

        setIsLoading(true);
        setError('');

        const currentContent = select('core/editor').getEditedPostContent();

        try {
            const response = await fetch('https://chat.orderease.cn/api/proxy.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    message: mode === 'continue' ? 
                        `继续写作以下内容：${currentContent}` : 
                        prompt,
                    stream: false
                })
            });

            const data = await response.json();
            
            if (data.result) {
                dispatch('core/editor').insertBlocks(
                    wp.blocks.createBlock('core/paragraph', {
                        content: mode === 'continue' ? 
                            currentContent + '\n\n' + data.result : 
                            data.result
                    })
                );
                setPrompt('');
            } else {
                throw new Error(data.error || '生成内容失败');
            }
        } catch (err) {
            setError(err.message || '生成内容时发生错误');
        } finally {
            setIsLoading(false);
        }
    };

    return wp.element.createElement(
        wp.element.Fragment,
        null,
        wp.element.createElement(
            PluginSidebarMoreMenuItem,
            {
                target: "ai-writer-sidebar"
            },
            "AI写作助手"
        ),
        wp.element.createElement(
            PluginSidebar,
            {
                name: "ai-writer-sidebar",
                title: "AI写作助手",
                icon: "admin-generic"
            },
            wp.element.createElement(
                PanelBody,
                null,
                error && wp.element.createElement(
                    Notice,
                    {
                        status: "error",
                        isDismissible: false
                    },
                    error
                ),
                wp.element.createElement(
                    ButtonGroup,
                    {
                        style: { marginBottom: '15px', width: '100%' }
                    },
                    wp.element.createElement(
                        Button,
                        {
                            isPrimary: mode === 'instruction',
                            onClick: () => setMode('instruction'),
                            style: { width: '50%' }
                        },
                        "指令写作"
                    ),
                    wp.element.createElement(
                        Button,
                        {
                            isPrimary: mode === 'continue',
                            onClick: () => setMode('continue'),
                            style: { width: '50%' }
                        },
                        "续写模式"
                    )
                ),
                mode === 'instruction' && wp.element.createElement(
                    TextareaControl,
                    {
                        label: "提示词",
                        help: "请输入AI写作提示词，例如：'写一篇关于人工智能的文章'",
                        value: prompt,
                        onChange: (value) => setPrompt(value),
                        rows: 6
                    }
                ),
                mode === 'continue' && wp.element.createElement(
                    "p",
                    {
                        className: "description"
                    },
                    "点击\"生成内容\"按钮，AI将基于当前文章内容继续写作。"
                ),
                wp.element.createElement(
                    Button,
                    {
                        isPrimary: true,
                        onClick: generateContent,
                        isBusy: isLoading,
                        disabled: isLoading || (mode === 'instruction' && !prompt.trim()),
                        style: { marginTop: '10px', width: '100%' }
                    },
                    isLoading ? "正在生成..." : "生成内容"
                )
            )
        )
    );
};

registerPlugin('ai-writer-plugin', {
    icon: 'admin-generic',
    render: AIWriterPlugin
}); 